package cn.dao; // 确保包名为 dao

import cn.entity.Student; // 确保导入正确的包
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class StudentDao extends BaseDao {

    public List<Student> getAll() throws SQLException {
        String sql = "SELECT * FROM students";

        Connection conn = getConnection();
        PreparedStatement pst = conn.prepareStatement(sql);
        ResultSet rs = pst.executeQuery();
        List<Student> students = new ArrayList<>();

        while (rs.next()) {
            Student student = new Student(
                    rs.getInt("id"),
                    rs.getString("name"),
                    rs.getInt("age"),
                    rs.getString("gender").charAt(0),
                    rs.getString("major")
            );
            students.add(student);
        }
        closeAll(conn, pst, rs); // 使用 BaseDao 中的 closeAll 方法
        return students;
    }

    public void addStudent(Student student) {
        String sql = "INSERT INTO students (name, age, gender, major) VALUES (?, ?, ?, ?)";
        try (Connection conn = getConnection();
             PreparedStatement pst = conn.prepareStatement(sql)) {
            pst.setString(1, student.getName());
            pst.setInt(2, student.getAge());
            pst.setString(3, String.valueOf(student.getGender()));
            pst.setString(4, student.getMajor());
            pst.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace(); // 考虑记录日志或抛出异常
        }
    }

    public void updateStudent(Student student) {
        String sql = "UPDATE students SET name = ?, age = ?, gender = ?, major = ? WHERE id = ?";
        try (Connection conn = getConnection();
             PreparedStatement pst = conn.prepareStatement(sql)) {
            pst.setString(1, student.getName());
            pst.setInt(2, student.getAge());
            pst.setString(3, String.valueOf(student.getGender()));
            pst.setString(4, student.getMajor());
            pst.setInt(5, student.getId());
            pst.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace(); // 考虑记录日志或抛出异常
        }
    }

    public void deleteStudent(int id) throws SQLException {
        String sql = "DELETE FROM students WHERE id = ?";
        try (Connection conn = getConnection();
             PreparedStatement pst = conn.prepareStatement(sql)) {
            pst.setInt(1, id);
            pst.executeUpdate();
        }
    }
}
